package com.sam.im.heiqun.uis.activities;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.media.Image;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;
import com.bumptech.glide.request.target.SimpleTarget;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.CommontsEntity;
import com.sam.im.heiqun.entities.FeedPraisesEntity;
import com.sam.im.heiqun.entities.ImFriendEntivity;
import com.sam.im.heiqun.entities.ImMessage;
import com.sam.im.heiqun.entities.ImageSendEntity;
import com.sam.im.heiqun.entities.MyCircleItem;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.entities.beans.ImageInfoBean;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.MediaUtil;
import com.sam.im.heiqun.uis.adapters.ChatRecyclerAdapter;
import com.sam.im.heiqun.uis.dialogs.ItemSelectorDialog;
import com.sam.im.heiqun.uis.dialogs.MyAlertDialogManages;
import com.sam.im.heiqun.utils.FileUtil;
import com.sam.im.heiqun.utils.JsonUtil;
import com.sam.im.heiqun.utils.MyDialog;
import com.sam.im.heiqun.utils.PathUtil;
import com.sam.im.heiqun.utils.RxJavaUtil;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.GlideUtils;
import com.yuyh.library.utils.ScreenUtil;
import com.yuyh.library.utils.TimeUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;
import com.sam.im.heiqun.utils.StringUtils;

/**
 * Created by yiw on 2016/1/6.
 */
public class ImagePagerActivity extends BaseSwipeBackActivity {
    public static final String INTENT_IMGURLS = "imgurls";
    public static final String INTENT_POSITION = "position";
    public static final String INTENT_IMAGESIZE = "imagesize";
    @BindView(R.id.pre_v_back)
    ImageView preVBack;
    @BindView(R.id.tv_year)
    TextView tvYear;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.activity_title)
    RelativeLayout activityTitle;
    @BindView(R.id.bt_parise)
    Button btParise;
    @BindView(R.id.bt_comment)
    Button btComment;
    @BindView(R.id.tv_comment)
    TextView tvComment;
    @BindView(R.id.tv_parise)
    TextView tvParise;
    @BindView(R.id.dtail)
    RelativeLayout dtail;
    @BindView(R.id.tvtext)
    TextView tvtext ;
    @BindView(R.id.title_nums)
    TextView titleNums ;
    @BindView(R.id.txt_down)
    TextView txt_down ;
    private List<View> guideViewList = new ArrayList<View>();
    private LinearLayout guideGroup;
    public ImageSize imageSize;
    private int startPos;
    private int selectePos = 0;
    private ArrayList<ImageInfoBean> imgUrls;
    private MyCircleItem.ListBean circleItem  ;
    private int parise = -1  ;

    public static void startImagePagerActivity(Context context, List<ImageInfoBean> imgUrls, int position, ImageSize imageSize) {
        Intent intent = new Intent(context, ImagePagerActivity.class);
        intent.putParcelableArrayListExtra(INTENT_IMGURLS, new ArrayList<>(imgUrls));
        intent.putExtra(INTENT_POSITION, position);
        intent.putExtra(INTENT_IMAGESIZE, imageSize);
        context.startActivity(intent);
    }
//    public static void startImagePagerActivity(Context context, List<String> imgUrls, int position, ImageSize imageSize,boolean canForward) {
//        Intent intent = new Intent(context, ImagePagerActivity.class);
//        intent.putStringArrayListExtra(INTENT_IMGURLS, new ArrayList<String>(imgUrls));
//        intent.putExtra(INTENT_POSITION, position);
//        intent.putExtra(INTENT_IMAGESIZE, imageSize);
//        intent.putExtra(INTENT_CAN_FORWARD,canForward);
//        context.startActivity(intent);
//    }
//    public static class ImageInfo{
//
//        private String url;
//        private boolean canForward;
//    }
    private void getIntentData() {
        startPos = getIntent().getIntExtra(INTENT_POSITION, 0);
        imgUrls = getIntent().getParcelableArrayListExtra(INTENT_IMGURLS);
        imageSize = (ImageSize) getIntent().getSerializableExtra(INTENT_IMAGESIZE);
        circleItem = (MyCircleItem.ListBean) getIntent().getSerializableExtra("circlebean");
    }
   /* private void addGuideView(LinearLayout guideGroup, int startPos, ArrayList<String> imgUrls) {
        if (imgUrls != null && imgUrls.size() > 0) {
            guideViewList.clear();
            for (int i = 0; i < imgUrls.size(); i++) {
                View view = new View(this);
                view.setBackgroundResource(R.drawable.selector_guide_bg);
                view.setSelected(i == startPos ? true : false);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(getResources().getDimensionPixelSize(R.dimen.gudieview_width),
                        getResources().getDimensionPixelSize(R.dimen.gudieview_heigh));
                layoutParams.setMargins(10, 0, 0, 0);
                guideGroup.addView(view, layoutParams);
                guideViewList.add(view);
            }
        }
    }*/

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        try {
            return super.dispatchTouchEvent(ev);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @OnClick({R.id.pre_v_back, R.id.bt_parise, R.id.bt_comment, R.id.txt_down})
    public void onViewClicked(View view) {

        switch (view.getId()) {
            case R.id.pre_v_back:
                finish();
                break;
            case R.id.bt_parise:
                if (circleItem!=null){
                    String feedId = circleItem.getFeedId();
                    String s = btParise.getText().toString();
                    if (getResources().getString(R.string.zan).equals(s)){
                        PGService.getInstance().getparise(ToolsUtils.getMyUserId(),feedId).subscribe(new AbsAPICallback<ValidateEntivity>() {
                            @Override
                            protected void onResultError(ApiException ex) {
                                ToolsUtils.showToast(ImagePagerActivity.this, getResources().getString(R.string.zan_fail));
                            }

                            @Override
                            public void onNext(ValidateEntivity validateEntivity) {
                                if (validateEntivity != null) {
                                    ToolsUtils.showToast(ImagePagerActivity.this,validateEntivity.getInfo());
                                    btParise.setText(getResources().getString(R.string.cancel));
                                    parise++ ;
                                    tvParise.setText(parise+"");
                                    EventBus.getDefault().post("点赞");
                                }
                            }
                        });
                    }else {
                        PGService.getInstance().delparise(feedId,ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<ValidateEntivity>() {
                            @Override
                            protected void onResultError(ApiException ex) {
                                ToolsUtils.showToast(ImagePagerActivity.this, getResources().getString(R.string.canler_fail));

                            }
                            @Override
                            public void onNext(ValidateEntivity validateEntivity) {
                                ToolsUtils.showToast(ImagePagerActivity.this,validateEntivity.getInfo());
                                btParise.setText(getResources().getString(R.string.zan));
                                parise-- ;
                                tvParise.setText(parise+"");
                                EventBus.getDefault().post("点赞");
                            }
                        });
                    }
                }
                break;
            case R.id.bt_comment:
                ToolsUtils.showToast(ImagePagerActivity.this, getResources().getString(R.string.this_commit_noopen));
                /*if (circleItem!=null){
                    String feedId = circleItem.getFeedId();
                }*/
                break;
            case R.id.txt_down:


                break;
        }
    }

    @Override
    protected String getTitleText() {
        return "";
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
        guideGroup = (LinearLayout) findViewById(R.id.guideGroup);
        getIntentData();
        if (circleItem != null) {
            String userId = circleItem.getUserId();
            long circleuserId = Long.parseLong(userId);//发布动态的用户id
            ImFriendEntivity friendById = ToolsUtils.getMyFriendForId(circleuserId);

            if (friendById != null|userId.equals(ToolsUtils.getMyUserId())) {
                dtail.setVisibility(View.VISIBLE);
            }else {
                dtail.setVisibility(View.GONE);
            }
            activityTitle.setVisibility(View.VISIBLE);
            //dtail.setVisibility(View.VISIBLE);
            String createTime = circleItem.getCreateTime();
            String feedImgs = circleItem.getFeedImgs();
            String feedText = circleItem.getFeedText();
            List<FeedPraisesEntity> imFeedPraises = circleItem.getImFeedPraises();
            List<CommontsEntity> imFeedComments = circleItem.getImFeedComments();
           // final List<PhotoInfo> photos = new ArrayList<>();
            imgUrls = new ArrayList<>();
            if (!StringUtils.isEmpty(feedImgs)) {
                if (feedImgs.contains(",")) {
                    String[] splitimg = feedImgs.split(",");
                    for (int e = 0; e < splitimg.length; e++) {
                        imgUrls.add(new ImageInfoBean(splitimg[e],true));
                    }
                } else {
                    imgUrls.add(new ImageInfoBean(feedImgs,true));
                }
            }
            imageSize = new ImagePagerActivity.ImageSize(ScreenUtil.getScreenWidth(this),ScreenUtil.getScreenHeight(this)-ScreenUtil.dp2px(95));
            parise = imFeedPraises.size();
            tvParise.setText(imFeedPraises.size()+"");
            tvComment.setText(imFeedComments.size()+"");
            String l = TimeUtil.getAllTime(Long.parseLong(createTime));
            String[] split = l.split(" ");
            tvYear.setText(split[0]);
            tvTime.setText(split[1]);
            if (!StringUtils.isEmpty(feedText)){
                tvtext.setVisibility(View.VISIBLE);
                tvtext.setText(feedText);
            }
            boolean ispraise = false ;
            if (imFeedPraises.size()>0){
                for (int i = 0; i < imFeedPraises.size(); i++) {
                    FeedPraisesEntity imFeedPraisesBean = imFeedPraises.get(i);
                    String userId1 = imFeedPraisesBean.getUserId();//点赞人的id  这里暂不取消赞 如果已经有赞就不能再次赞了
                    if (userId1.equals(ToolsUtils.getMyUserId())){
                        ispraise = true ;
                        break;
                    }
                }
            }
            if (ispraise){
                btParise.setText(getResources().getString(R.string.cancel));
            }else {
                btParise.setText(getResources().getString(R.string.zan));
            }
        }
        ImageAdapter mAdapter = new ImageAdapter(this);
        mAdapter.setDatas(imgUrls);
        mAdapter.setImageSize(imageSize);
        mAdapter.setOnLongClickListener(new ImageAdapter.OnLongClickListener() {

            @Override
            public void OnLongClick(final ImageView view, final ImageInfoBean path, int pos) {

                if(!path.isCanForward()){
                    return;
                }
                final ItemSelectorDialog<DialogItemBean> dialog = new ItemSelectorDialog<>(view.getContext());
                dialog.setTitle(null);
                dialog.setItems(new DialogItemBean[]{new DialogItemBean("发送给朋友"), new DialogItemBean("保存图片")});
                dialog.setDialogClickListener(new ItemSelectorDialog.DialogItemClickListener<DialogItemBean>() {
                    @Override
                    public void confirm(int position, DialogItemBean result) {
                        if (result.getText().equals("发送给朋友")) {

                            UserEntivity userEntivity = ToolsUtils.getUser();

                            final ImMessage imMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, ChatRecyclerAdapter.TO_USER_IMG, UUID.randomUUID().toString(),
                                    Long.parseLong(ToolsUtils.getMyUserId()), Constant.FROM_TYPE_MAM, 0, JsonUtil.toJson(new ImageSendEntity( path.getUrl(),path.isCanForward())), Constant.MESSAGE_TYPR_IMAGE,
                                    System.currentTimeMillis(), System.currentTimeMillis(), 0, path.getUrl(), ToolsUtils.getMyUserId() + "_" + "", 0, userEntivity.getHeadUrl());

                            Bundle bundle = new Bundle();
                            bundle.putSerializable("msg", imMessage);
                            bundle.putInt("tag", 11);startActivity(SelecteLocalFriendActivity.class, bundle);
                        } else if (result.getText().equals("保存图片")) {
                            Glide.with(ImagePagerActivity.this).load(imgUrls.get(selectePos).getUrl()).asBitmap().into(new SimpleTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                    File file = ToolsUtils.saveImageToGallery(resource, PathUtil.getImageDir());
                                    showToast(getResources().getString(R.string.image_save_success));
                                    MediaUtil.refreshMediaFileStore(ImagePagerActivity.this,file.getAbsolutePath(),null);
                                }
                            }); //方法中设置asBitmap可以设置回调类型
                        } else if("识别图中二维码".equals(result.getText())){
                            startActivity(WebViewActivity.newIntent(view.getContext(),result.getQrCodeResult()));
                        }
                    }
                });
                dialog.show();
                view.setDrawingCacheEnabled(true);
                Bitmap drawingCache = view.getDrawingCache();
                Bitmap bitmap = Bitmap.createBitmap(drawingCache);
                view.setDrawingCacheEnabled(false);
                RxJavaUtil.decodeQrCode(bitmap).compose(RxJavaUtil.<String>applySchedules())
                        .compose(RxJavaUtil.<String>bindDialogDismissLifeCycle(dialog))
                        .compose(ImagePagerActivity.this.<String>bindLifeCycle())
                        .subscribe(new AbsAPICallback<String>() {
                            @Override
                            public void onNext(String s) {
                                dialog.setItems(new DialogItemBean[]{new DialogItemBean("发送给朋友"),
                                        new DialogItemBean("保存图片"),
                                        new DialogItemBean("识别图中二维码",s)});
                            }

                            @Override
                            protected void onResultError(ApiException ex) {

                            }
                        });
            }
        });

        viewPager.setAdapter(mAdapter);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                titleNums.setText((position+1)+"/"+imgUrls.size());
                /*for (int i = 0; i < guideViewList.size(); i++) {
                    guideViewList.get(i).setSelected(i == position ? true : false);
                }*/
                selectePos = position ;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        viewPager.setCurrentItem(startPos);
        titleNums.setText((startPos+1)+"/"+imgUrls.size());
      //  addGuideView(guideGroup, startPos, imgUrls);
        selectePos = startPos ;
        mAdapter.setOnMyClickListener(new ImageAdapter.OnMyClickListenr() {
            @Override
            public void onClick(ImageView view) {
                Log.i("onclick----->","test");
                ImagePagerActivity.this.finish();
            }
        });

    }

    private static class ImageAdapter extends PagerAdapter implements View.OnClickListener{
        private List<ImageInfoBean> datas = new ArrayList<>();
        private LayoutInflater inflater;
        private Context context;
        private ImageSize imageSize;
        private ImageView smallImageView = null;

        private OnMyClickListenr myClickListenr;


        @Override
        public void onClick(View v) {
            myClickListenr.onClick((ImageView) v);
        }

        public interface  OnMyClickListenr{
            void onClick(ImageView view);
        }
        public void setOnMyClickListener(OnMyClickListenr listener){
            myClickListenr = listener;
        }
        private interface OnLongClickListener{
            void OnLongClick(ImageView view,ImageInfoBean path , int pos);
        }
        private OnLongClickListener mOnLongClickListener ;
        public void setOnLongClickListener(OnLongClickListener onLongClickListener){
            mOnLongClickListener = onLongClickListener;
        }

        public void setDatas(List<ImageInfoBean> datas) {
            if (datas != null)
                this.datas = datas;
        }

        public void setImageSize(ImageSize imageSize) {
            this.imageSize = imageSize;
        }

        public ImageAdapter(Context context) {
            this.context = context;
            this.inflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            if (datas == null) return 0;
            return datas.size();
        }


        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            View view = inflater.inflate(R.layout.item_pager_image, container, false);
            if (view != null) {
                final ImageView imageView = (ImageView) view.findViewById(R.id.image);

                if (imageSize != null) {
                    //预览imageView
                    smallImageView = new ImageView(context);
                    FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(imageSize.getWidth(), imageSize.getHeight());
                    layoutParams.gravity = Gravity.CENTER;
                    smallImageView.setLayoutParams(layoutParams);
                    smallImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    ((FrameLayout) view).addView(smallImageView);
                }

                //loading
                final ProgressBar loading = new ProgressBar(context);
                FrameLayout.LayoutParams loadingLayoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
                loadingLayoutParams.gravity = Gravity.CENTER;
                loading.setLayoutParams(loadingLayoutParams);
                ((FrameLayout) view).addView(loading);

                final ImageInfoBean imageInfoBean = datas.get(position);
                final String imgurl = imageInfoBean.getUrl();

                Glide.with(context)
                        .load(imgurl)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存多个尺寸
                        .thumbnail(0.1f)//先显示缩略图  缩略图为原图的1/10
                        .error(R.mipmap.ic_launcher)
                        .into(new GlideDrawableImageViewTarget(imageView) {
                            @Override
                            public void onLoadStarted(Drawable placeholder) {
                                super.onLoadStarted(placeholder);
                               /* if(smallImageView!=null){
                                    smallImageView.setVisibility(View.VISIBLE);
                                    Glide.with(context).load(imgurl).into(smallImageView);
                                }*/
                                loading.setVisibility(View.VISIBLE);
                            }

                            @Override
                            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                                super.onLoadFailed(e, errorDrawable);
                                /*if(smallImageView!=null){
                                    smallImageView.setVisibility(View.GONE);
                                }*/
                                loading.setVisibility(View.GONE);
                            }

                            @Override
                            public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> animation) {
                                super.onResourceReady(resource, animation);
                                loading.setVisibility(View.GONE);
                                /*if(smallImageView!=null){
                                    smallImageView.setVisibility(View.GONE);
                                }*/
                            }
                        });

                imageView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        if (null!=mOnLongClickListener)mOnLongClickListener.OnLongClick((ImageView) v,imageInfoBean, position);
                        return false;
                    }
                });

                container.addView(view, 0);
                smallImageView.setOnClickListener(this);

            }
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view.equals(object);
        }

        @Override
        public void restoreState(Parcelable state, ClassLoader loader) {
        }

        @Override
        public Parcelable saveState() {
            return null;
        }


    }

    @Override
    protected void onDestroy() {
        guideViewList.clear();
        super.onDestroy();
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_imagepager;
    }

    public static class ImageSize implements Serializable {

        private int width;
        private int height;

        public ImageSize(int width, int height) {
            this.width = width;
            this.height = height;
        }

        public int getHeight() {
            return height;
        }

        public void setHeight(int height) {
            this.height = height;
        }

        public int getWidth() {
            return width;
        }

        public void setWidth(int width) {
            this.width = width;
        }
    }

    class DialogItemBean  extends ItemSelectorDialog.Entity{

        private String qrCodeResult;

        public DialogItemBean(String text) {
            super(text);
        }

        public DialogItemBean(String text, String qrCodeResult) {
            super(text);
            this.qrCodeResult = qrCodeResult;
        }

        public String getQrCodeResult() {
            return qrCodeResult;
        }

        public void setQrCodeResult(String qrCodeResult) {
            this.qrCodeResult = qrCodeResult;
        }
    }
}
